﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PessMvc.Models;
using PessModel;
using System.Web.Security;
using PessMvc.Helpers;

namespace PessMvc.Lib
{
    public class AuthorBL:IAuthorBL
    {
        private PessModel.PESSEntities db;
        public AuthorBL()
        {
            db = new PessModel.PESSEntities();
        }
        public bool Add(AuthorModel model, out string errorMsg, string password = "111111")
        {
            if (this.IfAuthorExists(model.SerialNumber))
            {
                errorMsg = string.Format("{0} 已被使用，请输入其它用户名进行注册.", model.SerialNumber);
                return false;
            }
            MembershipCreateStatus createStatus;
            //expert.Email = expert.Email == null ? expert.SerialNumber + "@b.com" : expert.Email;
            MembershipUser user = Membership.CreateUser(model.SerialNumber, password, model.Email, "question", "answer", true, null, out createStatus);
            if (createStatus == MembershipCreateStatus.Success)
            {
                Roles.AddUserToRole(user.UserName, "Author");
                Author author = model.ConvertToAuthor();
                author.UserID = new Guid(user.ProviderUserKey.ToString());
                db.Authors.Add(author);
                db.SaveChanges();

                //user.Email = author.Email;
                Membership.UpdateUser(user);
                errorMsg = null;

                return true;// RedirectToAction("Details", "ExpertGroup", new { id = expert.ExpertGroupID });
            }
            else
            {
                errorMsg = createStatus.ToString();
                return false;
                //ModelState.AddModelError("", createStatus.ToString());
            }
        }

        private bool IfAuthorExists(string serialNumber)
        {            
            int count = (from a in db.Authors
                         where a.SerialNumber==serialNumber
                         select a).Count();            
            if (count > 0||Membership.GetUser(serialNumber)!=null)
            {
                return true;
            }
            else
            {
                return false;
            }           
        }

        public Author Find(string serialNumber)
        {
            return db.Authors.Find(serialNumber);
        }
    }
}